package com.fjp.heartguard.ui.checkversion

import android.content.Intent
import android.os.Bundle
import com.fjp.heartguard.app.App
import com.fjp.heartguard.app.Constants
import com.fjp.heartguard.app.base.BaseActivity
import com.fjp.heartguard.app.data.bean.AppVersion
import com.fjp.heartguard.app.ext.dp
import com.fjp.heartguard.app.weight.pop.UpdateVersionPop
import com.fjp.heartguard.databinding.ActivityCheckVersionBinding
import com.fjp.heartguard.viewmodel.CheckVersionViewModel
import com.heartguard.appupdate.utils.ApkUtils
import com.lxj.xpopup.XPopup
import me.hgj.jetpackmvvm.ext.parseState
import java.io.File

class CheckVersionActivity : BaseActivity<CheckVersionViewModel, ActivityCheckVersionBinding>(), UpdateVersionPop.InstallClickListener {
    lateinit var appVersion: AppVersion
    override fun initView(savedInstanceState: Bundle?) {
        mDatabind.viewModel = mViewModel
        mDatabind.click = ClickProxy()
        mViewModel.title.set("检查更新")
        appVersion = intent.getParcelableExtra<AppVersion>(Constants.INTENT_APP_VERISON)!!
        mDatabind.desTv.text = "有新版本：${appVersion.version}"

    }

    override fun createObserver() {
        super.createObserver()
        mViewModel.appVersion.observe(this) {
            parseState(it, {
                appVersion = it

            })
        }
    }

    inner class ClickProxy {
        fun clickUpdate() {
            showUpdateVersionPop()
        }
    }

    fun showUpdateVersionPop() {
        XPopup.Builder(this).dismissOnTouchOutside(false).dismissOnBackPressed(false).isDestroyOnDismiss(true).autoOpenSoftInput(false).popupWidth(400.dp.toInt()).asCustom(UpdateVersionPop(this, appVersion, this@CheckVersionActivity)).show()
    }

    override fun onClick(file: File) {
        runOnUiThread {
            if (!packageManager.canRequestPackageInstalls()) {
                App.apkFile = file
                ApkUtils.startPackageInstallActivity(this)
            } else {
                ApkUtils.installAPK(this, file)
            }


        }

    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode != RESULT_OK) {
            return
        }
        if (requestCode == ApkUtils.GET_UNKNOWN_APP_SOURCES) {
            App.apkFile?.let { ApkUtils.installAPK(this, it) }

        }
    }
}